<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper" style="position: relative">
        <div class="search-wrapper-btn">
          <a-button type="link" @click="show = !show">
            <span v-if="!show">展开<a-icon type="down"/></span>
            <span v-else>收起<a-icon type="up"/></span>
          </a-button>
        </div>
        <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol" @keyup.enter.native="onQuery">
          <div class="mode_item">
            <a-form-model-item label="告警类型">
              <j-dict-select-tag v-model="form.alarmType" placeholder="请选择" :dictCode="alarmTypeDatas" />
            </a-form-model-item>
            <a-form-model-item label="手机号">
              <a-input v-model="form.phone" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="处置状态">
              <j-search-select-tag placeholder="请选择" v-model="form.status" :dictOptions="statusOptions" />
            </a-form-model-item>
          </div>
          <div class="mode_item" v-show="show">
            <a-form-model-item label="告警程度">
              <j-search-select-tag placeholder="请选择" v-model="form.alarmLevel" :dictOptions="alarmLevelOptions" />
            </a-form-model-item>
          </div>
          <div class="mode_item mode_item_none" v-show="show">
            <a-form-model-item label="告警更新时间" class="zdy-form-item-label">
              <a-radio-group buttonStyle="solid" v-model="form.timeType">
                <a-radio-button v-for="(item, key) in options" :key="key" :value="item.value">
                  {{ item.text }}
                </a-radio-button>
              </a-radio-group>
              <a-range-picker
                v-if="form.timeType === '0'"
                :allowClear="true"
                v-model="rangePickerTime"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                @change="rangePickerChange"
                style="margin-left: 10px"
              />
            </a-form-model-item>
          </div>
          <div style="margin-top: 20px">
            <a-form-model-item :wrapper-col="{ offset: 0 }" style="margin-bottom: 0">
              <a-button class="Indormation-list-CX" type="primary" @click="onQuery"> 查询 </a-button>
              <a-button class="Indormation-list-CX" style="margin-left: 10px" @click="onResetForm"> 重置 </a-button>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
    </a-card>
    <a-card :bordered="false">
      <!-- 操作按钮区域 -->
      <div class="table-operator" v-if="isOperation">
        <div>
          <a-button type="primary" @click="handleExport">导出</a-button>
          <a-button type="primary" @click="configureRule">配置告警规则</a-button>
        </div>
      </div>
      <!-- 表格展示 -->
      <div class="table-page-content">
        <custom-table
          ref="table"
          rowKey="uuid"
          :showAlert="true"
          :showSelection="true"
          :loading="loading"
          :columns="columns"
          :dataSource="pageData"
          @selectedRow="onSelectedRow"
          @change="onTableChange"
        >
          <!--操作-->
          <template slot="action" slot-scope="text, record">
            <a-button @click="handleDetails(record)" type="link" style="padding:0;">查看</a-button>
            <a-divider type="vertical" v-if="record.status == 0 && isOperation" />
            <a-button
              v-if="record.status == 0 && isOperation"
              @click="handleDispose(record)"
              type="link"
              style="padding:0;"
              >处置</a-button
            >
          </template>
          <template slot="phone" slot-scope="text, record">
            <span>{{ text }}</span>
            <a-tag v-if="record.isSamplePerson" style="margin-top:10px;" color="red">负样本人员</a-tag>
          </template>
        </custom-table>
      </div>
      <!--弹窗区域 -->
      <configure-rule-modal
        v-if="configureBool"
        :modelId="modelId"
        :taskId="taskId"
        :approvalId="approvalId"
        ref="ruleModalRef"
        @ok="modalFormOk"
        @close="modalFormClose"
      />
      <dispose-modal :taskId="taskId" ref="disposeModalRef" @ok="modalFormOk" />
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import * as alarmApi from '@/api/wxSmuggle/alarm.js'
import { getXzqhList, getDictItemsFromCache } from '@/api/api'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { drctAlarmType } from '@/utils/tenantFilter'
import { downLoadFileReader } from '@/utils/export-util/util'
import CustomTable from '@/components/zxd/Table/CustomTable'
import configureRuleModal from './modules/ruleModal'
import disposeModal from './modules/disposeModal'
import { querySimpleByPhoneList } from '@/utils/util'
export default {
  components: {
    CustomTable,
    configureRuleModal,
    disposeModal
  },
  mixins: [DisabledAuthFilterMixin],
  data() {
    return {
      moment,
      labelCol: { span: 6 },
      wrapperCol: { span: 17 },
      rangePickerTime: [],
      show: false,
      closeTip: false,
      loading: false,
      visible: false,
      handleModalBool: false,
      isDisabled: true,
      reloading: false,
      configureBool: false,
      selectKeys: [],
      form: {},
      modelId: null,
      taskId: null,
      incidentId: null,
      approvalId: null,
      alarmTypeDatas: null,
      statusOptions: [
        // { text: '全部', value: '', },
        { text: '已处置', value: '1' },
        { text: '未处置', value: '0' }
      ],
      alarmLevelOptions: [
        // { text: '全部', value: '', },
        { text: '红色告警', value: '3' },
        { text: '橙色告警', value: '2' },
        { text: '黄色告警', value: '1' }
      ],
      options: [
        { value: '2', text: '今天' },
        { value: '1', text: '昨天' },
        { value: '3', text: '近三天' },
        { value: '4', text: '近七天' },
        { value: '0', text: '自定义' }
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 60,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` //序号分页后连续
        },
        {
          title: '告警类型',
          dataIndex: 'alarmType',
          width: 115,
          align: 'center',
          customRender: (text, record) => {
            return this.filterMultiDictText(this.alarmTypeDatas, text)
          }
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          width: 110,
          align: 'center',
          scopedSlots: { customRender: 'phone' }
        },
        {
          title: '姓名/代号',
          dataIndex: 'targetName',
          width: 120,
          align: 'center'
        },
        {
          title: '告警详情',
          dataIndex: 'description',
          width: 100,
          align: 'center'
        },
        {
          title: '告警程度',
          dataIndex: 'alarmLevel',
          width: 80,
          align: 'center',
          customRender: (text, record) => {
            return (
              <span class={text == 1 ? 'text_color_1' : text == 2 ? 'text_color_2' : 'text_color_3'}>
                {this.getItemsFrom(this.alarmLevelOptions, text)}
              </span>
            )
          }
        },
        {
          title: '处置状态',
          dataIndex: 'status',
          width: 100,
          align: 'center',
          customRender: (text, record) => {
            return <span class={text == 0 ? 'text_color_3' : ''}>{this.getItemsFrom(this.statusOptions, text)}</span>
          }
        },
        {
          title: '告警时间',
          dataIndex: 'alarmTime',
          width: 100,
          align: 'center'
        },
        {
          title: '操作',
          width: 180,
          align: 'center',
          dataIndex: 'action',
          // slots: { title: 'customIsAction' },
          scopedSlots: { customRender: 'action' }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
        operationModule: 1 // 1.告警中心，2.告警一张图（审计日志用）
      },
      pageData: {},
      isOperation: true
    }
  },
  created() {
    this.alarmTypeDatas = drctAlarmType
    this.getRouteQuery(this.$route)
  },
  watch: {
    $route(data) {
      console.log(data)
      this.getRouteQuery(data)
    },
    taskId() {
      this.onQuery()
    }
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.form = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
      this.isDisabled = keys.length > 0 ? false : true
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable() {
      console.log(this.taskId)
      let form = Object.assign({}, { taskId: this.taskId }, this.form, this.pageFilter)
      this.loading = true
      alarmApi
        .getPageList(form)
        .then(res => {
          if (res.success) {
            this.pageData = res.result
            this.loading = false
            this.$refs.table.onClearRowKeys()
            //判断是否是负样本号码，并添加负样本标签(电话号码字段：phoneNumber传1，phone传2，msisdn传3)
            querySimpleByPhoneList(this, 2, this.pageData.records)
          } else {
            this.loading = false
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 导出
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.uuid).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.uuid ? [record.uuid] : []
      let params = Object.assign(
        {},
        {
          uuidList: selectList.length > 0 ? idList1 : idList2,
          taskId: this.taskId,
          ...this.form
        }
      )
      this.$confirm({
        title: `是否确认导出？`,
        okText: '确定',
        onOk() {
          alarmApi.exportXls(params).then(async res => {
            const fileName = '告警消息数据.xls'
            await downLoadFileReader(res, fileName)
            that.$refs.table.onClearRowKeys()
          })
        }
      })
    },
    // 弹窗成功接收
    modalFormOk(type) {
      this.onQuery()
      this.configureBool = false
    },
    modalFormClose() {
      this.configureBool = false
    },
    configureRule() {
      this.configureBool = true
      this.$nextTick(() => {
        this.$refs.ruleModalRef.add()
      })
    },
    // 详情
    handleDetails(record) {
      this.$router.push({
        path: '/alarmCenter/details',
        query: {
          ids: record.ids,
          uuid: record.uuid,
          taskId: record.taskId,
          isOperation: this.isOperation,
          operationModule: 3 // 1.告警中心，2.告警一张图, 3.告警中心-详情处置,4. 重点人管理（审计日志用）
        }
      })
    },
    handleDispose(record) {
      this.$refs.disposeModalRef.edit(record, 1) // 1.告警中心，2.告警一张图, 3.告警中心-详情处置,4. 重点人管理（审计日志用）
    },
    // 告警更新时间
    rangePickerChange(date) {
      this.$set(this.form, 'beginTime', date[0])
      this.$set(this.form, 'endTime', date[1])
    },
    /** 重新加载组件 */
    reload() {
      this.reloading = true
      this.$nextTick(() => (this.reloading = false))
    },
    filterMultiDictText(dictCode, text) {
      if (!text && text !== 0) return
      let datas = getDictItemsFromCache(dictCode)
      // return this.$filterMultiDictText(datas, text)
      return this.$filterDictText(datas, text)
    },
    getItemsFrom(datas, key) {
      let item = datas.filter(t => t['value'] == key)
      if (item && item.length > 0) {
        return item[0]['text']
      }
    },
    // 监听路由变化
    getRouteQuery($route) {
      if ($route.query && Object.keys($route.query).length > 0) {
        let query = $route.query
        if (query.modelId) {
          this.modelId = query.modelId
        }
        if (query.taskId) {
          this.taskId = query.taskId
        }
        if (query.incidentId) {
          this.incidentId = query.incidentId
        }
        if (query.approvalId) {
          this.approvalId = query.approvalId
        }
        let str = query.isOperation.toString()
        if (str == 'true') {
          this.isOperation = true //发起人
        } else {
          this.isOperation = false //审批人
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.mode_item {
  display: flex;
  border-bottom: 1px #dadada dashed;
  > div {
    flex: 0 0 30%;
  }
  & > * {
    width: 100%;
    margin-bottom: 0;
    padding: 5px 0;
  }
  &.mode_item_none {
    > div {
      flex: inherit;
    }
  }
  .zdy-form-item-label {
    /deep/.ant-form-item-label {
      width: 100px;
    }
    &.xzqh-form-item-label {
      /deep/.ant-form-item-control-wrapper {
        .ant-form-item-children {
          display: -webkit-box;
        }
      }
      /deep/.area-select {
        // margin-top: 4px;
        line-height: 1;
      }
      /deep/.select-tag {
        width: 162px !important;
        margin-left: 10px;
        margin-top: 3px;
      }
      // /deep/.area-select .area-selected-trigger {
      //   line-height: 1.15;
      // }
      // /deep/.ant-select-lg .ant-select-selection--single{
      //   height: 34px;
      // }
      // /deep/.ant-select-lg .ant-select-selection__rendered {
      //   line-height: 34px;
      //   font-size: 14px;
      // }
    }
  }
}
.search-wrapper-btn {
  position: absolute;
  right: 0;
  top: 15px;
  z-index: 1;
}
/deep/.table-operator {
  display: flex;
  justify-content: space-between;
}
/deep/.table-custom-cols {
  top: -48px !important;
}
.custom-ewm {
  padding: 14px;
  background-color: #fff;
  border: 1px #ccc solid;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
}
/deep/.ant-dropdown-menu-item {
  text-align: center;
  border-bottom: 1px #f5f5f5 solid;
  &:last-child {
    border-bottom: 0;
  }
}
/deep/.anticon.anticon-down {
  font-size: 14px !important;
}

.table-page-content {
  /deep/.ant-table-thead > tr > th,
  /deep/.ant-table-tbody > tr > td {
    padding-left: 0;
    padding-right: 0;
  }
  /deep/.ant-table-thead > tr:first-child > th:first-child,
  /deep/.ant-table-tbody > tr > td:first-child {
    padding-left: 10px;
  }
  .text_color_1 {
    color: #bfbf00;
    padding-right: 6px;
  }
  .text_color_2 {
    color: #f59a23;
    padding-right: 6px;
  }
  .text_color_3 {
    color: #d9001b;
    padding-right: 6px;
  }
}
</style>
